#include "registerfunctionality.h"
#include "Modules/registermodule.h"

#include <Modules/TcpNetwork.h>
registerFunctionality::registerFunctionality(std::shared_ptr<NetworkInterface> network,
                                             std::shared_ptr<ModuleInterface> module)
    : FunctionalityInterface()
    , m_network(network)
    , m_module(module)
{
    m_module->initialize();
    m_network->connect("172.21.93.12", 10002);

    //连接信号与槽
    auto tcpNetwork = std::dynamic_pointer_cast<TcpNetwork>(m_network);

    QObject::connect(tcpNetwork.get(),
                     &TcpNetwork::dataArrival,
                     this,
                     &registerFunctionality::onDataArrival);
}

bool registerFunctionality::executeFunction()
{
    QByteArray data = m_module->execute();
    if (data.isEmpty()) {
        std::cerr << "Failed to execute module!" << std::endl;
        return false;
    }

    m_network->sendData(data);
    return true;
}

void registerFunctionality::setParameters(const QString &phoneNumber, const QString &passwd)
{
    registerModule *rm = dynamic_cast<registerModule *>(m_module.get());
    rm->setPhoneNumberPasswd(phoneNumber, passwd);
}

void registerFunctionality::onDataArrival(qint64 readBytes)
{
    //这里应该是将数据处理交给证书处理模块的
    QByteArray data = m_network->readData(readBytes);
    qDebug() << "45 data size :" << data.size();
    bool ret = m_module->handleReceiveData(data); //这个成功只是说数据处理是正确的，不代表插入成功。
    //不管处理成功还是失败，都会有提示消息
    if (ret) {
        // qDebug() << "注册成功"; //需要发送信号说明注册成功
        registerModule *rm = dynamic_cast<registerModule *>(m_module.get());
        QString response_data = rm->getResponseResult();
        if (isRegistrationSuccessful(response_data))
            emit registraSuccessed(response_data);
        else
            emit registraFailed(response_data);
    } else {
        qDebug() << "handleReceiveData error!";
    }
}

bool registerFunctionality::isRegistrationSuccessful(const QString &data)
{
    if (data.indexOf("Failed") == -1) {
        //等于-1说明没有找到，因此应该返回的是true
        qDebug() << "Failed";
        return true;
    } else
        return false;
}
